package com.bjgzy.courselive.mvp.presenter;

import android.app.Application;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.commonsdk.entity.RightOrderInfo;
import com.eduhzy.ttw.commonsdk.holder.AutoBaseViewHolder;
import com.eduhzy.ttw.teacher.mvp.contract.MineOrderContract;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


/**
 * @author xubo
 * @date 2018-8-3 10:37:55
 */
@ActivityScope
public class MineOrderPresenter extends BasePresenter<MineOrderContract.Model, MineOrderContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    private int page = 1;
    private int pageSize = 10;

    @Inject
    BaseQuickAdapter<RightOrderInfo, AutoBaseViewHolder> mAdapter;

    @Inject
    public MineOrderPresenter(MineOrderContract.Model model, MineOrderContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }


    public void getShopOrderInfo(boolean pullToRefresh, int orderStatus) {
        if (pullToRefresh) {
            page = 1;
        } else {
            page++;
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("orderStatus", orderStatus);
        map.put("currentPage", page);
        map.put("pageSize", pageSize);
        map.put("userId", SPUtils.getInstance().getString(Constants.USERID));
        mModel.getShopOrderInfo(map)
                .retryWhen(new RetryWithDelay(2, 3))
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    if (pullToRefresh)
                        mRootView.showLoading();
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    if (pullToRefresh)
                        mRootView.hideLoading();
                }).compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<List<RightOrderInfo>>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<List<RightOrderInfo>> data) {
                        mRootView.updatePagerTitle(data.getCount());
                        if (data.isResult() && ObjectUtils.isNotEmpty(data.getData())) {
                            if (pullToRefresh) {
                                mAdapter.setNewData(data.getData());
                            } else {
                                mAdapter.addData(data.getData());
                            }
                            if (data.getData().size() < pageSize) {
                                mAdapter.loadMoreEnd(true);
                            } else {
                                mAdapter.loadMoreComplete();
                            }
                        } else {
                            if (pullToRefresh) {
                                mAdapter.getData().clear();
                                mAdapter.notifyDataSetChanged();
                            }
                            if (ObjectUtils.isNotEmpty(data.getMessage())) {
                                mRootView.showMessage(data.getMessage());
                            }
                        }
                        if (ObjectUtils.isEmpty(data.getData()) && ObjectUtils.isEmpty(mAdapter.getData())) {
                            mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.no_data));
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        if (pullToRefresh) {
                            if (t instanceof ConnectException || t instanceof UnknownHostException) {
                                mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.no_network));
                            } else {
                                mAdapter.setEmptyView(RxUtil.getEmptyView(mRootView.getActivity(), RxUtil.ErrorCode.load_error));
                            }
                        } else {
                            mAdapter.loadMoreFail();
                        }
                    }
                });
    }
}
